package data

import (
	"fmt"
	"yunj/pkg/global"
	"yunj/pkg/yunj/app/model"
	"yunj/pkg/yunj/core/db"
)

// 初始化角色数据库
func InitRoleDbData() (err error) {
	roleDb := db.Model(&model.AdminRole{})
	tableName := roleDb.GetTableName()
	// 创建数据表
	tableSql := "CREATE TABLE IF NOT EXISTS `" + tableName + "` (" +
		"`id` int NOT NULL AUTO_INCREMENT," +
		"`name` varchar(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '名称'," +
		"`code` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '标识'," +
		"`intro` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '简介'," +
		"`auths` json DEFAULT NULL COMMENT '拥有的权限。如：[\"auth1\",\"auth2\",\"auth3\"]'," +
		"`sort` int unsigned NOT NULL DEFAULT '0' COMMENT '排序'," +
		"`created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP," +
		"`updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP," +
		"`state` tinyint unsigned NOT NULL DEFAULT '11' COMMENT '11 正常 | 22 回收站 | 33 已删除'," +
		"PRIMARY KEY (`id`) USING BTREE," +
		"UNIQUE KEY `uk_code` (`code`) USING BTREE" +
		") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci ROW_FORMAT=DYNAMIC COMMENT='成员角色表';"
	err = global.MySQL.Exec(tableSql).Error
	if err != nil {
		err = fmt.Errorf("创建数据表%s失败！%v", tableName, err)
		return
	}
	// 判断是否存在数据，不存在则加入系统数据
	var count int64
	err = global.MySQL.Model(&model.AdminRole{}).Count(&count).Error
	if err != nil {
		err = fmt.Errorf("数据表%s数据是否存在查询异常！%v", tableName, err)
		return
	}
	if count <= 0 {
		err = global.MySQL.Exec("INSERT INTO `yj_admin_role` VALUES (1, '超级管理员', 'administrator', '拥有所有权限', NULL, 0, '2022-01-01 00:00:00', '2022-01-01 00:00:00', 11);").Error
		if err != nil {
			err = fmt.Errorf("数据表%s系统insert数据异常！%v", tableName, err)
			return
		}
	}
	return
}
